import { Body, Controller, Get, Param, Post, Query } from '@nestjs/common';
import { FollowService } from './follow.service';
import { FollowUserDto } from './dto/follow-user.dto';
import { ApiOperation } from '@nestjs/swagger';

@Controller('follow')
export class FollowController {
  constructor(private readonly followService: FollowService) {}

  @Post()
  @ApiOperation({ summary: '关注用户' })
  async followUser(@Body() dto: FollowUserDto) {
    await this.followService.followUser(dto.followerId, dto.followedId);
    return { message: 'Followed successfully' };
  }

  @Post('unfollow')
  @ApiOperation({ summary: '取消关注用户' })
  async unfollowUser(@Body() dto: FollowUserDto) {
    await this.followService.unfollowUser(dto.followerId, dto.followedId);
    return { message: 'Unfollowed successfully' };
  }

  @Get(':userId/following')
  @ApiOperation({ summary: '获取关注用户列表(分页)' })
  async getFollowingList(
    @Param('userId') userId: number,
    @Query('page') page: number = 1,
    @Query('limit') limit: number = 10,
  ) {
    const followingData = await this.followService.getFollowingList(
      userId,
      page,
      limit,
    );

    // 转换为所需的数据结构
    const formattedList = followingData.items.map((item) => ({
      id: item.followed.id,
      username: item.followed.username,
      avatar: item.followed.avatar || '',
      fansCount: item.followed.follower_count,
      description: item.followed.bio || '',
      followed: item.created_at.toISOString(),
    }));

    return {
      items: formattedList,
      total: followingData.total,
      page: followingData.page,
      limit: followingData.limit,
      totalPages: followingData.totalPages,
    };
  }
  @Get(':userId/followers')
  @ApiOperation({ summary: '获取粉丝用户列表(分页)' })
  async getFollowersList(
    @Param('userId') userId: number,
    @Query('page') page: number = 1,
    @Query('limit') limit: number = 10,
  ) {
    const followersData = await this.followService.getFollowersList(
      userId,
      page,
      limit,
    );
  
    // 获取当前用户关注的用户列表（用于判断是否关注了粉丝）
    const followingIds = await this.followService.getFollowingIds(userId);
    
    // 转换为所需的数据结构，并添加 isFollowed 字段
    const formattedList = followersData.items.map((item) => ({
      id: item.follower.id,
      username: item.follower.username,
      avatar: item.follower.avatar || '',
      fansCount: item.follower.follower_count,
      description: item.follower.bio || '',
      followed: item.created_at.toISOString(),
      isFollowed: followingIds.includes(item.follower.id), // 判断当前用户是否关注了这个粉丝
    }));
  
    return {
      items: formattedList,
      total: followersData.total,
      page: followersData.page,
      limit: followersData.limit,
      totalPages: followersData.totalPages,
    };
  }
}
